package com.weblog.exception;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.crypto.CryptoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import com.weblog.msg.SystemEnum;
import com.weblog.msg.UserOperationEnum;

/**
 * 定义全局异常处理类
 * 
 * @author zhw
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 注解声明异常处理方法 handleException() 就会处理所有 Controller 层抛出的 Exception 及其子类的异常
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	ModelAndView handleException(Exception e) {
		ModelAndView modelAndView = new ModelAndView();
		// 凭证错误信息
		if (e instanceof IncorrectCredentialsException) {
			// 用户名密码错误
			modelAndView.addObject("msg", UserOperationEnum.U001.getMsg());
			modelAndView.setViewName("/user/userlogin");
		}
		// 认证错误信息
		if (e instanceof AuthenticationException) {
			// 用户名不存在系类
			modelAndView.addObject("msg", UserOperationEnum.U003.getMsg());
			modelAndView.setViewName("/user/userlogin");
		}
		LOGGER.error(e.getMessage(), e);
		return modelAndView;
	}

	/**
	 * 500服务器异常信息
	 * @param e
	 * @return
	 */
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public ModelAndView ServerException(Exception e) {
		ModelAndView modelAndView = new ModelAndView();
		if (e instanceof CryptoException) {
			// redis没有启动
			modelAndView.addObject("msg", SystemEnum.S001.getMsg());
			modelAndView.setViewName("/error/500");
		}
		LOGGER.error(e.getMessage(), e);
		return modelAndView;
	}
	
	
	/**
	 * 404notfound异常配置
	 * @param e
	 * @return
	 */
	@ResponseStatus(value = HttpStatus.FORBIDDEN)
	public ModelAndView NOTFoundException(Exception e) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("msg", SystemEnum.S002.getMsg());
		modelAndView.setViewName("/error/404");
		LOGGER.error(e.getMessage(), e);
		return modelAndView;
	}

	
	/**
	 * 处理所有业务异常
	 * 
	 * @param e
	 * @return
	 */
	/*
	 * @ExceptionHandler(BusinessException.class)
	 * 
	 * @ResponseBody AppResponse handleBusinessException(BusinessException e) {
	 * LOGGER.error(e.getMessage(), e);
	 * 
	 * AppResponse response = new AppResponse(); response.setFail(e.getMessage());
	 * return response; }
	 */
}
